#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include <sys/stat.h>
#include<dirent.h>
#include<fcntl.h>
#include<unistd.h> 
#include<pthread.h>


void ls(char* dir);
int main(int argc, char* args[])
{
	if(argc == 1){
		ls(".");
	}
	else{
		for(int i = 1; i < argc; i++){
			ls(args[i]);
		}
	}

	return 0;
}

void ls(char* dir)
{
	printf("dir is %s\n", dir);
	DIR* dp = opendir(dir);
	if(!dp){
		perror("open dir error");
		exit(1);
	}
	
	struct dirent* det; 
	errno = 0;
	while(det = readdir(dp)){
		printf("det->d_name is %s\n", det -> d_name);
		if(strcmp(det->d_name, "..") == 0 || strcmp(det->d_name, ".") == 0)
			continue;
		struct stat stbuf;
		if(stat(det->d_name, &stbuf) < 0){
			perror("get stat error");
			exit(1);
		}
		if(S_ISDIR(stbuf.st_mode)){
			printf("this is a dir\n");
			char newpath[256];
			printf("before sprintf newpath is %s\n", newpath);
			sprintf(newpath, "%s/%s", dir, det->d_name);
			printf("after sprintf newpath is %s\n", newpath);
			ls(newpath);
		}
		else{
			printf("%*s,%*d\n", 40, det->d_name, -5, stbuf.st_size);
		}

	}

	if(errno){
		perror("readdir error");
		exit(1);
	}

	return;
}


